import { useState, useEffect, useRef } from "react";
import { getRandom, getRndInteger } from "@/utils";
import style from "./index.module.less";
import User from "@/components/User";
import Dialog from "./components/Dialog";

function App() {
  const numCell = 4;
  const numRow = 13;
  const [quick, setQuick] = useState('');
  const [num, setNum] = useState(5);
  const [symbol, setSymbol] = useState("+");
  const [cell] = useState(Array.from({ length: numCell }, (v, i) => i));
  const [row, setRow] = useState([]);
  const [width] = useState(`${100 / cell.length}%`);
  const [fontSize] = useState({
    fontSize: "30px",
  });

  useEffect(() => {
    const arr = getNums();
    setRow(arr);
  }, []);

  useEffect(() => {
    getData()
  }, [quick, num, symbol])

  // 生成数字数组
  const getNums = (): any => {
    const arr: any = [];
    for (let i = 0; i < numCell * numRow; i++) {
      const num1 = getRndInteger(1, num)
      let num2 = getRndInteger(1, num)
      if (symbol === '-') {
        num2 = getRndInteger(1, num1)
      }
      arr.push({
        num1,
        num2,
        symbol: symbol,
      });
    }
    return arr;
  };

  // 快速获取减十法
  const getNums10 = (): any => {
    const arr: any = [];
    let num1 = 0
    let num2 = 0
    for (let i = 0; i < numCell * numRow; i++) {
      // 减十法
      num1 = 10
      num2 = getRndInteger(1, num1)
      
      arr.push({
        num1,
        num2,
        symbol: '-',
      });
    }
    return arr;
  };

  // 获取结果
  const getData = () => {
    let arr = []
    if (quick) {
      arr = getNums10();
    } else {
      arr = getNums();
    }
    setRow(arr.concat());
  }


  // 显示弹框
  // 创建ref
  const refDialog: any = useRef()
  const handlerEmitClick = () => {
    refDialog.current.showDialog()
  };
  // 刷新
  const handlerRefresh = () => {
    getData()
  };

  type Values = {
    num: number
    symbol: string
    quick: '1' | '2'
  }
  // 弹框的回调
  const onSuccess = (values: Values) => {
    const { num: _num, symbol: _symbol, quick: _quick } = values;
    setQuick(_quick[0])
    setNum(_num)
    setSymbol(_symbol)
  }

  return (
    <div>
      <User emitClick={() => handlerEmitClick()} emitRefresh={() => handlerRefresh()} />
      {/* 编辑框 */}
      <Dialog ref={refDialog} onSuccess={onSuccess} />
      <div className={style.box} style={fontSize}>
        {row.map((item: any, i: number) => {
          return (
            <div key={`${i}num`} className={style.itemBox} style={{ width }}>
              {item.num1} {item.symbol} {item.num2} =
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;
